# -*- coding:utf-8 -*-
import os

from ruamel import yaml


def __read_yaml():
    yml = []

    def inn_reload():
        del yml[:]

    def inner_read_yaml():
        if len(yml) == 0:
            try:
                with open('configure/config.yml', 'r') as f:
                    yml.append(yaml.load(f, Loader=yaml.Loader))
            except Exception:
                return {}
        return yml[0] or {}

    inner_read_yaml.reload = inn_reload
    return inner_read_yaml


_read_yaml = __read_yaml()


def _write_yaml(yml):
    """ 写入内容到yaml文件
    @param yml: 字典对象 
    """
    with open('configure/config.yml', 'w') as f:
        yaml.dump(yml, f, Dumper=yaml.RoundTripDumper)

    _read_yaml.reload()


def read(key=None):
    """ 读取
    @param key: 键
    @return: 返回该键对应的值，键为空时返回所有数据。
    """
    yml = _read_yaml()
    if isinstance(key, dict):
        k,v = key.keys()[0], key.values()[0]
        return yml[k].get(v, '')
    elif key:
        return yml.get(key, '')
    else:
        return yml


def write(key, value):
    """ 写入（有则覆盖，无则新增）
    @param key: 键
    @param value: 值
    """
    yml = _read_yaml()

    if isinstance(value, dict):
        old_value = yml.get(key, None)
        if isinstance(old_value, dict):
            old_value.update(value)
        else:
            yml.update({key: value})
    else:
        yml.update({key: value})
    _write_yaml(yml)


def remove(key):
    """ 移除
    @param key: 键
    """
    yml = _read_yaml()
    if isinstance(key,dict):
        yml[key.keys()[0]].pop(key.values()[0])
    else:
        yml.pop(key, None)
    _write_yaml(yml)


def reset(yml):
    """ 覆盖yaml文件内容
    @param yml: 字典对象 
    """
    _write_yaml(yml)


if __name__ == '__main__':
    # print read()
    # write('wwws', {'username': 'wwws1'})
    # print read()
    print read({'9b41c845-4087-4a45-8084-ebaa52b096cb': 'add_time'})
